import { LoginParam } from "@Tea/model"
import { UserRepository } from "../repo/UserRepository"
import { Token } from "../dao/Token"

export class AccountContext {
  private static inst: AccountContext
  private repo: UserRepository = UserRepository.getInstance()

  // 单例
  public static getInstance() {
    if (!AccountContext.inst) {
      AccountContext.inst = new AccountContext()
    }

    return AccountContext.inst
  }

  // 检查账户
  public async verify(data: LoginParam) {
    const { account, password } = data
    const user = await this.repo.getUser(account, password)

    return user
  }

  // 退出登录
  public loginOut(hashToken: string) {
    const token = Token.getInstance()

    return token.cacheDel(hashToken)
  }

  // 改变权限
  upgradeAuthority(userId: number) {
    return this.repo.changAuthority(userId, "admin")
  }

  downgradeAuthority(userId: number) {
    return this.repo.changAuthority(userId, "user")
  }

  async checkAccount(account: string) {
    return (await this.repo.findAccount(account))[0]
  }

  register(account: string, username: string, password: string) {
    return this.repo.register(account, username, password)
  }
}